package net;

import gui.Player;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import statics.Constants;

import net.protocols.ServerProtocol;

public class Server {

	public static void main(String[] args){
		new Server();
	}
	
	
	private int _players = Constants._PLAYERS;
	
	private NetworkConnection[] conns;
	private Player[] players;
	private ServerSocket server;
	
	//private 
	
	public Server(){
		players = new Player[_players];
		conns = new NetworkConnection[_players];
		
		try {
			server = new ServerSocket(8889);
			print("#! Server created...");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		searchForClients();
	}

	private void searchForClients() {
		print("#! Searching for players...");
		int _connectedPlayers = 0;
			while(_connectedPlayers < _players){
				try {
					print("#! Trying to find #"+(_connectedPlayers+1)+" player");
					NetworkConnection acceptedConnection = new NetworkConnection(
							(_connectedPlayers+1),server.accept(), this);
					conns[_connectedPlayers] = acceptedConnection;
					acceptedConnection.start();
					_connectedPlayers++;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			print("#! All clients ("+_connectedPlayers+") have been found...");
			print("#! Waiting a bit to setup game...");
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			print("#! Trying to setup game...");
			for(NetworkConnection con : conns){
				con.startGame();
			}
			//Alle clients gevonden Start game protocol
	}
	
	public void print(String message){
		System.out.println(message);
	}
	
}
